/*
 * Copyright 2016-2019 yoara
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package yhao.infra.web.controller;

import com.alibaba.fastjson.JSONObject;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import springfox.documentation.annotations.ApiIgnore;
import yhao.infra.common.util.encrypt.RSAUtil;
import yhao.infra.web.common.security.encrypt.helper.RSAEncryptHelper;

import java.security.KeyPair;
import java.security.interfaces.RSAPublicKey;

/**
 * 提供秘钥服务的Controller
 *
 * @author yoara
 */
@Lazy
@RestController
@RequestMapping(value = "/common/encryptToken/",produces = { "application/json;charset=UTF-8" })
@ApiIgnore
public class EncryptTokenController extends BaseController {
    @RequestMapping(value = "initRasCode")
    public String initRasCode() {
        JSONObject json = new JSONObject();

        KeyPair keyPair = RSAUtil.makeKeyPair();
        // 公钥
        RSAPublicKey publicKey = (RSAPublicKey) keyPair.getPublic();

        String key = rsaEncryptHelper.putRSAPriveteKey(keyPair,60*10);
        json.put("status", "OK");
        json.put(RSAEncryptHelper.RSA_PARAM_KEY,key);
        json.put(RSAEncryptHelper.RSA_PUBLIC_MODULES,publicKey.getModulus().toString(16));
        json.put(RSAEncryptHelper.RSA_PUBLIC_EXPONENT,publicKey.getPublicExponent().toString(16));
        return successInfo(json);
    }

    @RequestMapping(value = "checkRasCode")
    public String checkRasCode(){
        JSONObject json = new JSONObject();
        json.put("result", rsaCheck(null));
        return successInfo(json);
    }
}
